package com.sleep.blog.controller;

import com.sleep.blog.utils.QiNiuYunUtils;
import com.sleep.blog.vo.ErrorCode;
import com.sleep.blog.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author Sleep-6000
 * @date 2021/10/12
 */
@RestController
@RequestMapping("upload")
public class UploadController {

    @Autowired
    private QiNiuYunUtils qiNiuYunUtils;

    /**
     * 上传图片
     * @param file 图片文件
     * @return 上传结果
     */
    @PostMapping
    public Result upload(@RequestParam("image") MultipartFile file) {
        //原始文件名称
        String originalFilename = file.getOriginalFilename();
        //唯一的文件名称
        String fileName = UUID.randomUUID() + "." + StringUtils.substringAfterLast(originalFilename, ".");
        //文件上传地址 七牛云
        boolean upload = qiNiuYunUtils.upload(file, fileName);
        if (upload) {
            return Result.success(QiNiuYunUtils.URL + fileName);
        }
        return Result.fail(ErrorCode.UPLOAD_FAIL.getCode(), ErrorCode.UPLOAD_FAIL.getMsg());
    }

}
